﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using ConfigLibrary;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Tools.Excel;
using System.Threading;



namespace bldgportal
{
    public partial class bldgportal : Form
    {
        
        WebBrowser edds = new WebBrowser();
        WebBrowser observation = new WebBrowser();
        WebBrowser gridpage = new WebBrowser();
        public static observationpage observ;
        public static grid observgrid;
        public static page newpage;          
        public static HtmlElementCollection observinfo;        
        public static HtmlElement eddspw;
        public static HtmlElement eddsbutton;
        public static HtmlElement strseq;
        public static HtmlElement citye;
        public static HtmlElement ste;
        public static HtmlElement opene;
        private Config config;
        public static string email;
        public static string password;
        private string host;
        private int port;
        string sid;
        string dl;
        bool loggedin = false;        
        Excel.Application xls;
        Excel._Workbook wboo;
        public static Excel._Worksheet wsc;
        public static Excel._Worksheet wsp;
        DateTime dt;
        int lastrow;
        int ppg = 0;
        HtmlElement ppgse;
        string ppgs;
        int pagecount;
        int pagenumber;
        bool loop = false;        
        public static int p = 0;
        public static bool firstten = true;
        public static bool secondten = false;
        public static string name;
        public static int pp;
        public static bool firstpass = false;
        public static int set = 0;
       
        
        
        public bldgportal()
        {
            InitializeComponent();
            emailpassword();
            //openxl();
            //this.Load += new EventHandler(bldgportal_Load);





            //header();
            eddsload();
        }

        void eddswk_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            
        }

        void bldgportal_Load(object sender, EventArgs e)
        {
            
        }

        public void emailpassword()
        {
            Stream s = File.Open(Properties.Settings.Default.CONFIG, FileMode.Open);
            BinaryFormatter b = new BinaryFormatter();
            config = (Config)b.Deserialize(s);
            s.Close();
            config.GetMailInfo(out host, out email, out password, out port);
        }

        private void openxl()
        {
            xls = new Excel.Application();
            xls.Visible = true;
            xls.DisplayAlerts = false;
            wboo = xls.Workbooks.Open("\\\\u:\\Reports\\Open Observations\\Open Observations.xlsx", 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            wsc = wboo.Worksheets.Add(Type.Missing, wboo.Worksheets[wboo.Worksheets.Count], Type.Missing, Type.Missing);
            wsp = wboo.Worksheets[wboo.Worksheets.Count - 1];
            dt = DateTime.Today;
            string wsn = String.Format("{0:MM.dd.yy}", dt);
            wsc.Name = wsn;
            xls.DisplayAlerts = true;
        }

        private void header()
        {
            wsc.Range["A1"].Value = "Str#";
            wsc.Range["B1"].Value = "Seq#";
            wsc.Range["C1"].Value = "City";
            wsc.Range["D1"].Value = "St";
            wsc.Range["E1"].Value = "#Open";
        }


        private void eddsload()
        {

            edds.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(edds_DocumentCompleted);
            edds.AllowNavigation = true;
            edds.Navigate("https://www.bldgportal.com/Login.aspx", false);
        }

        void edds_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (loggedin == false)
            {
                eddspw = edds.Document.GetElementById("PasswordTextBox");
                eddspw.SetAttribute("value", password);
                eddsbutton = edds.Document.GetElementById("LoginButton");
                eddsbutton.InvokeMember("click");
                loggedin = true;
            }

            else if (loggedin == true)
            {
                observ = new observationpage();
                observ.Load += new EventHandler(observ_Load);
                observ.ShowDialog();                
            }
        }

        void observ_Load(object sender, EventArgs e)
        {
            HtmlElement table = edds.Document.GetElementById("UserIDTable");
            HtmlElementCollection devlog = table.GetElementsByTagName("td");
            string devlogid = devlog[7].InnerHtml;
            int a = devlogid.IndexOf("SID=");
            int b = devlogid.IndexOf("');");
            sid = devlogid.Substring(a + 4, b - (a + 4));
            HtmlElement devlogin = edds.Document.GetElementById(sid);
            dl = "https://www.bldgportal.com/DeviationLog/LoginDirect.aspx?SID=" + sid;           
            observation.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(observation_DocumentCompleted);
            observation.AllowNavigation = true;
            observation.Navigate(dl, false);
        }       

        void observation_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            iteration it = new iteration();
            it.nextpage();
        }

        

















        //void observgrid_Load(object sender, EventArgs e)
        //{
        //    gridpage.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(gridpage_DocumentCompleted);
        //    gridpage.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(gridpage_DocumentCompleted);
        //    gridpage.AllowNavigation = true;
        //    gridpage.Navigate("http://www.bldgportal.com/DeviationLog/Application/RecordList_Grid.aspx", false);
        //}

        //void gridpage_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        //{
        //    lastrow = wsc.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row;
        //    HtmlElement table;
        //    table = gridpage.Document.GetElementById("dataGrid");
            
        //    if (table == null)
        //    {
        //        for (int i = 0; i < 10; i++)
        //        {
        //            observgrid.Dispose();
        //            loop = true;
        //            observgrid = new grid();
        //            observgrid.Load -= new EventHandler(observgrid_Load);
        //            observgrid.Load += new EventHandler(observgrid_Load);
        //            observgrid.ShowDialog();                    
        //        }
        //    }

        //    HtmlElementCollection rows;
        //    rows = table.GetElementsByTagName("tr");
        //    HtmlElement row;
        //    row = rows[25];
        //    HtmlElementCollection pagerow;
        //    pagerow = row.GetElementsByTagName("a");           
        //    pagecount = pagerow.Count;

        //    if (loop == true)
        //    {
        //        if (pagenumber > 1 && pagenumber <= 10)
        //        {
        //            ppg = pagenumber;
        //            loop = false;
        //        }
        //        else if (pagenumber > 10 && pagenumber <= 20)
        //        {
        //            pagerow[pagecount - 1].InvokeMember("click");
        //            ppg = pagenumber - 10;
        //            loop = false;
        //        }
        //        else if (pagenumber > 20 && pagenumber <= 30)
        //        {
        //            if (clickone == false)
        //            {
        //                pagerow[pagecount - 1].InvokeMember("click");
        //            }
        //            else if (clickone == true && clicktwo == false)
        //            {
        //                pagerow[pagecount - 1].InvokeMember("click");
        //                ppg = pagenumber - 10;
        //                loop = false;
        //            }
                    
        //        }
        //    }

        //    ppgse = pagerow[ppg];
        //    ppgse.InvokeMember("click");            
        //    ppgs = ppgse.InnerHtml;
        //    if (ppgs != "...")
        //    {
        //        pagenumber = (Convert.ToInt32(ppgs) - 1);
        //    }
        //    rows = table.GetElementsByTagName("tr");
        //    int rowscount = rows.Count;
        //    for (int r = 0; r < rowscount - 1; r++)
        //    {                
        //        observinfo = rows[r].GetElementsByTagName("td");
        //        opene = observinfo[5];
        //        string open = opene.InnerHtml;
        //        if (open == "0")
        //        {
        //            continue;
        //        }
        //        strseq = observinfo[2];
        //        string ss = strseq.InnerHtml;
        //        string[] sss = ss.Split(new Char[] { '-' });
        //        string str = sss[0];
        //        string seq = sss[1];
        //        wsc.Cells[lastrow + 1, 1] = str;
        //        wsc.Cells[lastrow + 1, 2] = seq;
        //        citye = observinfo[3];
        //        string city = citye.InnerHtml;
        //        wsc.Cells[lastrow + 1, 3] = city;
        //        ste = observinfo[4];
        //        string st = ste.InnerHtml;
        //        wsc.Cells[lastrow + 1, 4] = st;                
        //        wsc.Cells[lastrow + 1, 5] = open;
        //        lastrow++;
        //        //if (ppgs == 1 && ppg == pagecount && pagecount < 12)
        //        //{
        //        //    break;
        //        //}
        //    }
            
        //    ppg++;

        //    if (ppgs == "..." )
        //    {
        //        ppg = 1;                
        //    }
        //    if (pagenumber > 10 && pagecount <= 11)
        //    {
        //        ppg = 3;
        //    }

        //    //if (ppg == 11 && ppgs == 1)
        //    //{
        //    //    ppg = 1;
                
        //    //}
              
        //}        
    }
}
